<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h2>{{ isLoginMode ? '用户登录' : '用户注册' }}</h2>
        <el-switch
            v-model="isLoginMode"
            active-text="登录"
            inactive-text="注册"
            @change="resetForm"
        />
      </div>

      <el-form
          ref="loginFormRef"
          :model="form"
          :rules="rules"
          label-width="80px"
          class="login-form"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              prefix-icon="User"
          />
        </el-form-item>

        <!-- 真实姓名（仅注册时显示） -->
        <el-form-item v-if="!isLoginMode" label="真实姓名" prop="realName">
          <el-input
              v-model="form.realName"
              placeholder="请输入真实姓名"
              prefix-icon="User"
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              show-password
              prefix-icon="Lock"
          />
        </el-form-item>

        <!-- 邮箱（仅注册时显示） -->
        <el-form-item v-if="!isLoginMode" label="邮箱" prop="email">
          <el-input
              v-model="form.email"
              placeholder="请输入邮箱"
              prefix-icon="Message"
          />
        </el-form-item>

        <!-- 手机号（仅注册时显示） -->
        <el-form-item v-if="!isLoginMode" label="手机号" prop="phone">
          <el-input
              v-model="form.phone"
              placeholder="请输入手机号"
              prefix-icon="Iphone"
          />
        </el-form-item>

        <!-- 确认密码（仅注册时显示） -->
        <el-form-item v-if="!isLoginMode" label="确认密码" prop="confirmPassword">
          <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              show-password
              prefix-icon="Lock"
          />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              @click="handleSubmit"
              :loading="loading"
              class="submit-btn"
          >
            {{ isLoginMode ? '登录' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-footer">
        <el-button link @click="toggleMode">
          {{ isLoginMode ? '没有账号？立即注册' : '已有账号？立即登录' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/pinia'
import { ElMessage } from 'element-plus'
import { login, register } from '@/api/userApi'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const loginFormRef = ref()

// 是否为登录模式
const isLoginMode = ref(true)

// 加载状态
const loading = ref(false)

// 表单数据
const form = reactive({
  username: '',
  realName: '',
  password: '',
  email: '',
  phone: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '真实姓名长度在2到10个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 检查是否已登录
if (userStore.isLoggedIn) {
  router.push('/')
}

// 切换登录/注册模式
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (loginFormRef.value) {
    loginFormRef.value.resetFields()
  }
}

// 处理提交
const handleSubmit = async () => {
  try {
    // 验证表单
    await loginFormRef.value.validate()
    loading.value = true

    if (isLoginMode.value) {
      // 登录逻辑
      await handleLogin()
    } else {
      // 注册逻辑
      await handleRegister()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    loading.value = false
  }
}

// 处理登录
const handleLogin = async () => {
  try {
    const loginData = {
      username: form.username,
      password: form.password
    }

    const response = await login(loginData)

    // 存储用户信息
    userStore.setToken(response.token)
    userStore.setUserInfo(response)

    ElMessage.success('登录成功')

    // 检查是否有重定向路径
    const redirect = router.currentRoute.value.query.redirect
    if (redirect) {
      router.push(redirect)
    } else {
      router.push('/')
    }
  } catch (error) {
    const errorMsg = error.response?.data?.message || error.message || '登录失败'
    ElMessage.error(errorMsg)
  } finally {
    loading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  try {
    const registerData = {
      username: form.username,
      realName: form.realName,
      password: form.password,
      email: form.email,
      phone: form.phone
    }

    const response = await register(registerData)

    ElMessage.success('注册成功，请登录')

    // 注册成功后切换到登录模式
    isLoginMode.value = true
    resetForm()
  } catch (error) {
    const errorMsg = error.response?.data?.message || error.message || '注册失败'
    ElMessage.error(errorMsg)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 480px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  padding: 40px;
  animation: fadeIn 0.5s ease;
}

.login-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  font-size: 24px;
}

.login-form {
  margin-top: 20px;
}

.submit-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  margin-top: 10px;
}

.login-footer {
  margin-top: 20px;
  text-align: center;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 600px) {
  .login-card {
    padding: 30px 20px;
    width: 90%;
  }

  .login-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>